#pragma once

#include <iostream>
#include <memory>
#include "Epoller.hpp"
#include "InetAddr.hpp"
#include "Socket.hpp"
#include "Log.hpp"
#include "Connection.hpp"
#include "IOService.hpp"
#include "Reactor.hpp"
#include "Protocol.hpp"
#include "Calculator.hpp"

using namespace SocketModule;
using namespace LogModule;

//专门负责获取链接的模块
class Listener : public Connection
{
public:
    Listener(int port)
        :_listensock(std::make_unique<TcpSocket>()),
        _port(port)
    {
        _listensock->BuildTcpSocket(port);
        SetSockfd(_listensock->Fd());
        SetEvents(EPOLLIN|EPOLLET);
    }
    int Sockfd()
    {
        return _listensock->Fd();
    }
    virtual void Sender() override
    {

    }
    virtual void Recver() override
    {
        while(true)
        {
            InetAddr peer;
            int aerrno = 0;
            //acceptt 非阻塞的时候,就是IO,我们就像处理对应的read一样处理accept
            int sockfd = _listensock->Accepter(&peer,&aerrno);
            if(sockfd > 0)
            {
                //我们要讲sockfd添加到epoll里面,epollserver只认识connection
                LOG(LogLevel::INFO) << "Listener -> Accepter" ;
                //2.sockfd包装成connection
                auto conn = std::make_shared<IOService>(sockfd);
                conn->RegisterOnMessage(HandlerRequest);
                //3.将conn添加到对应的epoll模型中
                GetOwner()->InsertConnection(conn);
            }
            else
            {
                if(aerrno == EAGAIN || aerrno == EWOULDBLOCK)
                {
                    LOG(LogLevel::DEBUG) << "accepter all connection ... done";
                    break;
                }
                else if(aerrno == EINTR)
                {
                    LOG(LogLevel::DEBUG) << "accepter inter by signal,continue";
                    continue;
                }
                else
                {
                    LOG(LogLevel::WARNING) << "accepter error ... ignore";
                    break;
                }
            }
        }
    }
    virtual void Excepter()override
    {

    }
    ~Listener()
    {
        _listensock->Close();
    }
private:
    int _port;
    std::unique_ptr<Socket> _listensock;
};

